package middleware

import (
	"GO/common"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

//注册一个解析token的中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取authorization header
		tokenString := c.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": 401,
				"msg":    "权限不足",
			})
			//// 若验证不通过，不再调用后续的函数处理
			c.Abort()
			return
		}
		tokenString = tokenString[7:]

		token, claims, err := common.ParseToken(tokenString)
		//解析失败
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": 401,
				"msg":    "权限不足",
			})
			c.Abort()
			return
		}

		//验证通过后获取claim中的那些username，account，Class
		username := claims.Username
		account := claims.Account
		class := claims.Class
		// var id int
		db := common.GetDB()
		type id_ struct {
			id int
		}
		var result id_
		//生成的信息不在数据库中
		if r := db.Raw("SELECT id FROM user_information WHERE username = ? AND account = ? AND class = ?", username, account, class).Scan(&result).RowsAffected; r == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": 401,
				"err":    err,
			})
			c.Abort()
			return
		}

		//如果用户存在，将username，account，class写入上下文
		c.Set("username", username)
		c.Set("account", account)
		c.Set("class", class)

		c.Next()
	}
}
